//
//  ZMNetErrorView.m
//  ZMKitDemo
//
//  Created by zm on 2018/6/19.
//  Copyright © 2018年 zm. All rights reserved.
//

#import "ZMNetErrorView.h"
@interface ZMNetErrorView ()

@property (nonatomic,strong) UIImageView *iconImageView;
@property (nonatomic,strong) UILabel *desLabel;

@property (nonatomic,copy) ZMNetErrorViewRetryBlock retryBlock;

@end

@implementation ZMNetErrorView

+(void)showInView:(UIView *)view withRetryBolck:(ZMNetErrorViewRetryBlock)retryBlock {
    ZMNetErrorView *netErrorV = [[ZMNetErrorView alloc] initWithFrame:view.bounds];
    netErrorV.retryBlock = retryBlock;
    [view addSubview:netErrorV];
}

+(void)dismissFromView:(UIView *)view {
    if (!view || ![view isKindOfClass:[UIView class]]) {
        return;
    }
    for (UIView *v in view.subviews) {
        if ([v isKindOfClass:[self class]]) {
            ZMNetErrorView *netErrorV = (ZMNetErrorView *)v;
            netErrorV.retryBlock = nil;
            [netErrorV removeFromSuperview];
            break;
        }
    }
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.userInteractionEnabled = true;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(retry)];
        [self addGestureRecognizer:tap];
        
        [self setupViews];
    }
    return self;
}

-(void)retry {
    if (self.retryBlock) {
        self.retryBlock(self);
    }
}

- (void)setupViews {
    self.iconImageView = ({
        UIImageView *imageView = [UIImageView new];
        [self addSubview:imageView];
        imageView.image = [UIImage imageNamed:ZMKitConfig.shared.netErrorImageName?:@""];
        imageView;
    });
    
    self.desLabel = ({
        UILabel *label = [UILabel new];
        [self addSubview:label];
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"网络未连接，点击页面重试";
        label.font = [UIFont systemFontOfSize:14.0];
        label.textColor = UIColorFromRGB(0x999999);
        label;
    });
}

+ (BOOL)requiresConstraintBasedLayout { return true; }

- (void)updateConstraints {
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.bottom.equalTo(self.mas_centerY);
    }];
    [self.desLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.iconImageView.mas_bottom).offset(15);
        make.centerX.equalTo(self);
        make.width.equalTo(self);
    }];
    [super updateConstraints];
}

@end
